//
//  ZPBaseNavigationController.m
//  ZPIOSEducation
//
//  Created by 李伟 on 2016/11/23.
//  Copyright © 2016年 liwei. All rights reserved.
//

#import "ZPBaseNavigationController.h"

#define TOUCH_DISTANCE  150

@interface ZPBaseNavigationController ()

@property (strong , nonatomic) NSMutableArray *snapArray;
@property (assign , nonatomic) CGPoint        startPoint;
@property (strong , nonatomic) UIView         *backgroundView;
@property (strong , nonatomic) UIView         *blackMask;
@property (strong , nonatomic) UIImageView    *lastScreenShotImageView;
@property (assign , nonatomic) BOOL           isMoving;
@end

@implementation ZPBaseNavigationController

- (instancetype)initWithRootViewController:(UIViewController *)rootViewController{
    self = [super initWithRootViewController:rootViewController];
    if (self) {
        self.snapArray = [NSMutableArray arrayWithCapacity:2];
        self.canDragBack = YES;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationBar.barStyle = UIBarStyleBlackOpaque;
    self.navigationBar.barTintColor = zMainColor;
    self.navigationBar.tintColor    = white_color;
    [self.navigationBar setTitleTextAttributes:@{NSFontAttributeName:Z16,NSForegroundColorAttributeName:white_color}];
    self.navigationBar.translucent = NO;
    //[self setNavigationBackgroundImage];
    
    self.interactivePopGestureRecognizer.enabled = NO;
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPanGestureRecognizer:)];
    panRecognizer.delegate = self;
    [self.view addGestureRecognizer:panRecognizer];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:(BOOL)animated];
    if (self.snapArray.count == 0) {
        UIImage *capturedImage = [self capture];
        [self.snapArray addObject:capturedImage];
    }
}


-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if ([self capture]) {
        [self.snapArray addObject:[self capture]];
    }
    if (self.viewControllers.count == 1) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}


-(UIViewController*)popViewControllerAnimated:(BOOL)animated{
    [self.snapArray removeLastObject];
    return [super popViewControllerAnimated:animated];
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (self.viewControllers.count <= 1 || !self.canDragBack) return NO;
    return YES;
}


-(void)didPanGestureRecognizer:(UIPanGestureRecognizer*)pan{
    if (self.viewControllers.count <= 1 || !self.canDragBack) return;
    CGPoint touchPoint = [pan locationInView:K_WINDOW];
    if (pan.state == UIGestureRecognizerStateBegan) {
        self.startPoint = touchPoint;
        _isMoving = YES;
        [self addSnapView];
    } else if (pan.state == UIGestureRecognizerStateEnded) {
        if (touchPoint.x - self.startPoint.x>TOUCH_DISTANCE) {
            [UIView animateWithDuration:0.3 animations:^{
                [self doMoveViewWithX:Main_Screen_Width];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                [self popViewControllerAnimated:NO];
                CGRect frame = T_VIEW.frame;
                frame.origin.x = 0;
                T_VIEW.frame = frame;
                self.backgroundView.hidden = YES;
            }];
        }else {
            [UIView animateWithDuration:0.3 animations:^{
                [self doMoveViewWithX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                self.backgroundView.hidden = YES;
            }];
        }
        return;
    }else if (pan.state == UIGestureRecognizerStateCancelled){
        [UIView animateWithDuration:0.3 animations:^{
            [self doMoveViewWithX:0];
        } completion:^(BOOL finished) {
            _isMoving = NO;
            self.backgroundView.hidden = YES;
        }];
        return;
    }
    if (_isMoving) {
        [self doMoveViewWithX:touchPoint.x - self.startPoint.x];
    }
}


-(void)addSnapView{
    if (!self.backgroundView) {
        self.backgroundView = [[UIView alloc]initWithFrame:self.view.bounds];
        self.backgroundView.backgroundColor = [UIColor blackColor];
        [T_VIEW.superview insertSubview:self.backgroundView belowSubview:T_VIEW];
        self.blackMask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width , Main_Screen_Height)];
        self.blackMask.backgroundColor = [UIColor blackColor];
        [self.backgroundView addSubview:self.blackMask];
    }
    self.backgroundView.hidden = NO;
    if (self.lastScreenShotImageView) { [self.lastScreenShotImageView removeFromSuperview]; }
    UIImage *lastScreenShot = [self.snapArray lastObject];
    self.lastScreenShotImageView = [[UIImageView alloc] initWithImage:lastScreenShot];
    self.lastScreenShotImageView.frame = CGRectMake(0, 0, Main_Screen_Width,Main_Screen_Height);
    [self.backgroundView insertSubview:self.lastScreenShotImageView belowSubview:self.blackMask];
}


- (UIImage *)capture{
    UIGraphicsBeginImageContextWithOptions(T_VIEW.bounds.size, T_VIEW.opaque, 0.0);
    [T_VIEW.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


-(void)doMoveViewWithX:(CGFloat)x{
    x = x>Main_Screen_Height?Main_Screen_Width:x;
    x = x<0?0:x;
    CGRect frame = T_VIEW.frame;
    frame.origin.x = x;
    T_VIEW.frame = frame;
    switch (_popAnimationType) {
        case 0:
            [self animateionFromBehind:x];
            break;
        case 1:
            [self animationLiner:x];
            break;
        default:
            break;
    }
}


-(void)animateionFromBehind:(CGFloat)x{
    float coefficient = Main_Screen_Width*25;
    float scale = (x/coefficient)+0.96;
    float alpha = 0.4 - (x/800);
    _lastScreenShotImageView.transform = CGAffineTransformMakeScale(scale, scale);
    _blackMask.alpha = alpha;
}


-(void)animationLiner:(CGFloat)x{
    float coefficient = x/2;
    CGRect screenShotImageViewFrame = _lastScreenShotImageView.frame;
    screenShotImageViewFrame.origin.x = -Main_Screen_Width/2 + coefficient;
    _lastScreenShotImageView.frame = screenShotImageViewFrame;
    _blackMask.alpha = 0.3;
}


-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}


- (void)dealloc{
    self.snapArray = nil;
    [self.backgroundView removeFromSuperview];
    self.backgroundView = nil;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
